/*
 *  TitleScene.cpp
 *  SpaceTrader
 *
 *  Created by Jake on 10/6/12.
 *  Copyright 2012 __MyCompanyName__. All rights reserved.
 *
 */

#include "TitleScene.h"
#include "GuiTools.h"

state_t TitleScene::draw(SDL_Surface *screen, Player *player)
{

	TTF_Font *titleFont = TTF_OpenFont( "Futura.ttc", 50 );
	TTF_Font *buttonFont = TTF_OpenFont( "Futura.ttc", 20 );

	SDL_Color textColor = {255,255,255};
	
	SDL_Event event;
	state_t next_state = TITLE;
	
	//Initialize Objects
	GuiButton newGame(230,100);
	GuiButton loadGame(230,180);
	GuiButton combatDemo(230,260);
	GuiButton loginButton(230,340);
	GuiButton exit(230,410);

	SDL_Surface *background = load_image("Title.png",false);
	SDL_Surface *title_text = TTF_RenderText_Blended( titleFont, "SpaceTrader", textColor  );
	SDL_Surface *newGame_text = TTF_RenderText_Blended( buttonFont, "New Game", textColor  );
	SDL_Surface *loadGame_text = TTF_RenderText_Blended( buttonFont, "Load Game", textColor  );
	SDL_Surface *combatDemo_text = TTF_RenderText_Blended( buttonFont, "Combat Demo", textColor  );
	SDL_Surface *login_text = TTF_RenderText_Blended( buttonFont, "Login", textColor  );
	SDL_Surface *exit_text = TTF_RenderText_Blended( buttonFont, "Quit", textColor  );
	

	while (next_state==TITLE) {
		
		//Event Loop
		while (SDL_PollEvent(&event)) {
			if (newGame.handle_input(event) == CLICKED) next_state = STATS;
			if (loadGame.handle_input(event) == CLICKED) next_state = LOAD;
			if (combatDemo.handle_input(event) == CLICKED) next_state = COMBAT;
			if (loginButton.handle_input(event) == CLICKED) {
				std::string name = showLoginDialog(screen);
				if(name != "") {
					player->setName(name);
					next_state = LOADDB;
				} else {
					next_state = TITLE;
				}
			}
			if (exit.handle_input(event) == CLICKED) next_state = QUIT;
			if (event.type==SDL_QUIT) next_state = QUIT;
			
		}
	
		//Apply objects
		SDL_FillRect(screen, &screen->clip_rect, SDL_MapRGB(screen->format, 0xFF, 0xFF, 0xFF));
        apply_surface( 0, 0, background, screen );
		newGame.show(screen);
		loadGame.show(screen);
		combatDemo.show(screen);
		loginButton.show(screen);
		exit.show(screen);
		apply_surface(250, 115, newGame_text, screen );
		apply_surface(250, 195, loadGame_text, screen );
		apply_surface(240, 275, combatDemo_text, screen );
		apply_surface(280, 355, login_text, screen );
		apply_surface(280, 425, exit_text, screen );


		apply_surface(180, 0, title_text, screen );

		//Update the screen
		if ( SDL_Flip( screen ) == -1 ) {
			std::cerr << "Error Updating screen." << std::endl;
		}
		/*if(SDL_GetTicks() < 1000 / FPS)
			SDL_Delay((1000/FPS)-SDL_GetTicks());*/
	}
	SDL_FreeSurface(background);
	SDL_FreeSurface(title_text);
	SDL_FreeSurface(newGame_text);
	SDL_FreeSurface(loadGame_text);
	SDL_FreeSurface(login_text);
	SDL_FreeSurface(combatDemo_text);
	SDL_FreeSurface(exit_text);
	TTF_CloseFont(titleFont);
	TTF_CloseFont(buttonFont);

	return next_state;
}
